package com.qf.service.impl;

import com.qf.constant.SsmConstant;
import com.qf.entity.User;
import com.qf.enums.ExceptionInfoEnum;
import com.qf.exception.SsmException;
import com.qf.mapper.UserMapper;
import com.qf.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    //异步校验用户名
    @Override
    public void checkUsername(String username) {
        //1.封装查询条件
        User param = new User();
        param.setUsername(username);
        //2.调用UserMapper进行查询
        int count = userMapper.selectCount(param);
        if(count!=0){
            log.info("【异步校验用户名】用户名不可用,username={}",username);
            throw new SsmException(11,"用户名不可用!!!");
        }
    }


    //执行注册
    @Override
    public void register(User user) {
//        1. 生成一个盐
        String salt= UUID.randomUUID().toString();
//        2. 对密码进行和加盐.			->		shiro-core-1.4.0
        String newPassword= new Md5Hash(user.getPassword(),salt,SsmConstant.HASH_ITERATIONS).toString();
//        3. 封装数据.
        user.setPassword(newPassword);
        user.setSalt(salt);
//        4. 执行添加.
        int count = userMapper.insertSelective(user);
//        5. 判断注册是否成功.
        if(count!=1){
            log.info("【注册账号】注册账号失败，user={}",user);
            throw new SsmException(ExceptionInfoEnum.USER_REGISTER_ERROR);
        }
    }

    //执行登录
    @Override
    public User login(String username, String password) {
//        1. 根据用户名查询用户信息.
        User user = new User();
        user.setUsername(username);
        User user1 = userMapper.selectOne(user);
//        2. 如果用户信息为null -> 用户名不正确.
        if(user1==null){
            log.info("【用户登录】用户名不存在，username={}",username);
            throw new SsmException(ExceptionInfoEnum.USER_USERNAME_ERROR);
        }
//        3. 将用户输入的密码进行加密和加盐.
        String newPassword=new Md5Hash(password,user1.getSalt(), SsmConstant.HASH_ITERATIONS).toString();
//        4. 判断密码是否正确(不正确) -> 密码不正确.
        if(!newPassword.equals(user1.getPassword())){
            log.info("【用户登录】密码不正确,password={}",password);
            throw new SsmException(ExceptionInfoEnum.USER_PASSWORD_ERROR);
        }
//        5. 返回用户信息.
        return user1;
    }

}
